package com.california.pay.config;

import com.california.pay.exception.BusinessException;
import com.california.pay.result.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StopWatch;

import javax.validation.ConstraintViolationException;
import java.util.concurrent.Callable;

/**
 * facade 层模板类
 */
@Slf4j
@Service
public class FacadeServiceTemplate {

    /**
     * 执行门面模板
     */
    public <T, R> CommonResult<T> execute(String tip, Callable<R> callable) {
        //initTraceId();
        StopWatch stopWatch = new StopWatch(">>>>>>>调用Dubbo" + tip);
        stopWatch.start();
        CommonResult<T> commonResult;
        try {
            R result = callable.call();
            if (result == null) {
                commonResult = CommonResult.success();
            } else if (result instanceof CommonResult) {
                commonResult = (CommonResult) result;
            } else {
                commonResult = CommonResult.success((T) result);
            }

        } catch (Exception e) {
            log.error(">>>>>>>调用Dubbo" + tip + "异常--- : " + e.getMessage(), e);
            if (e instanceof BusinessException
                    || e instanceof IllegalArgumentException || e instanceof ConstraintViolationException) {
                commonResult = CommonResult.failure(e);
            } else {
                commonResult = CommonResult.failure(CommonErrors.UNDEFINED.getCode(), "系统异常，请稍后重试");
            }
        }

        stopWatch.stop();
        log.info(">>>>>>>stopwatch: {}", stopWatch.prettyPrint());

        return commonResult;
    }


}
